package com.common.app.utls

import android.annotation.SuppressLint
import android.view.View
import android.view.ViewGroup
import com.common.app.R
import com.common.app.data.bean.KeyPre
import com.common.app.data.bean.VersionResBean
import com.common.app.databinding.CustomDialogApkDownloadBinding
import com.common.app.helper.AppConfigHelper
import com.common.base.app.extras.*
import com.common.base.app.fragment.BaseDialogFragment
import com.common.base.utils.SpUtilsManagement
import kotlin.math.roundToInt

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/8/29
 * <p>
 * 描述：APK下载框
 * <p>
 * 修订历史：
 */
class ApkDownloadDialog : BaseDialogFragment<CustomDialogApkDownloadBinding>() {

    companion object {
        fun newInstance(version: VersionResBean?): ApkDownloadDialog {
            val dialog = ApkDownloadDialog()
            dialog.isCoerce = version?.forced == 2
            dialog.version = version
            return dialog
        }
    }

    override fun getViewBinding() = CustomDialogApkDownloadBinding.inflate(layoutInflater)
    override fun getTheme(): Int = R.style.dialog
    override fun getSelfHeight() = dpDimenPx(R.dimen.dp_410).toInt()

    //开始下载更新
    private var updateClick: (() -> Unit)? = null

    //已经下载的 直接安装
    private var installClick: (() -> Unit)? = null

    //是否强制更新
    private var isCoerce: Boolean = false
    private var version: VersionResBean? = null

    var isDownload = false
    override fun getCancelable() = !isCoerce

    @SuppressLint("SetTextI18n")
    override fun initView(view: View) {
        super.initView(view)
        setShowPositionCenter()
        //强制更新
        isCoerce.yes {
            mViewBinding.checkBox.gone()
            mViewBinding.downloadHintTv.gone()
            mViewBinding.downloadClose.gone()
        }
        mViewBinding.downloadVersionTv.text = "v${version?.versionName}"
        mViewBinding.downloadInfoTv.text = version?.descr
        isDownload.yes { installApp() }
        val apkDownloadHint = AppConfigHelper.getApkDownloadHint()
        mViewBinding.checkBox.isChecked = apkDownloadHint
    }

    override fun initEvent() {
        super.initEvent()
        mViewBinding.apply {
            downloadClose.setOnClickListener { dismiss() }
            //下载
            updateButton.setOnClickListener {
                val butStr = updateButton.text.toString()
                if (butStr.contains("安装")) {
                    installClick?.invoke()
                    return@setOnClickListener
                }
                updateClick?.invoke()
                checkBox.gone()
                downloadHintTv.gone()
                downloadFailTv.gone()
                updateButton.invisible()
                downloadingTv.visible()
                downloadProgress.visible()
                isCancelable = false

            }
            downloadHintTv.setOnClickListener { checkBox.isChecked = !checkBox.isChecked }
            checkBox.setOnCheckedChangeListener { _, isChecked ->
                SpUtilsManagement.putBoolean(
                    KeyPre.KEY_APK_DOWNLOAD_HINT + TimeUtils.getTodayData(),
                    isChecked
                )
            }
        }
    }

    fun setOnUpdateClick(click: (() -> Unit)) {
        this.updateClick = click
    }

    fun setOnInstallClick(click: (() -> Unit)) {
        this.installClick = click
    }

    @SuppressLint("SetTextI18n")
    fun setViewLayoutParams(w: Int, ratio: Float) {
        (w <= 0).yes { return }
        mViewBinding.apply {
            val lp = vLine.layoutParams as ViewGroup.LayoutParams

            val viewPW = w * ratio
            vLine.visible()
            if (viewPW.roundToInt() > 0) {
                lp.width = viewPW.roundToInt()
                vLine.layoutParams = lp
                val percentage = ratio * 100
                (percentage >= 90).yes { progressIcon.gone() }
                if (percentage > 10) {
                    tvPercentageNum.visible()
                    tvPercentageNum.text = "${percentage.roundToInt()}%"
                } else {
                    tvPercentageNum.gone()
                }
            }
        }
    }

    //APP已经下载，直接安装
    fun installApp() {
        mViewBinding.apply {
            downloadProgress.gone()
            downloadFailTv.gone()
            updateButton.visible()
            updateButton.text = "立即安装"
        }
    }


    //下载失败
    fun downloadFailed() {
        mViewBinding.apply {
            downloadProgress.gone()
            downloadingTv.gone()
            updateButton.visible()
            downloadFailTv.visible()
            updateButton.text = "重新下载"
        }
    }
}